package com.ztom.agent.log;


import com.ztom.agent.config.TraceConfig;

import java.util.HashMap;
import java.util.Map;

/**
 * @author ZhangTao
 */
public final class LoggerFactory {

    private static final TraceConfig config = TraceConfig.getInstance();

    private static final Map<String, ILogger> LOGGER_MAP = new HashMap<>();

    static {
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            for (ILogger writer : LOGGER_MAP.values()) {
                writer.preCloseLog();
            }

            for (ILogger writer : LOGGER_MAP.values()) {
                writer.closeLog();
            }
        }));
    }

    public static synchronized ILogger getLogger(String logFile) {
        logFile = logFile.trim();

        ILogger logger = LOGGER_MAP.get(logFile);
        if (logger != null) {
            return logger;
        }

        logger = new AutoRollingLogger(logFile, config.getLogRollingTimeUnit(), config.getLogReserveCount());
        LOGGER_MAP.put(logFile, logger);
        return logger;
    }
}
